#!/usr/bin/env python

import os, sys
from net import app_auto_update
from config import WS_PID_FILE
from common import pidinfo
from log import out, err
from time import sleep
from center import Center

def save_pid():
    f = open(WS_PID_FILE, 'w')
    pid = str(os.getpgrp())
    f.write(pid)
    f.close()

def do_work(sec):
    c = None
    try:
        app_auto_update()
        c = Center()
        c.run()
    except Exception as e:
        err('蚂蚁程序遇到错误, %s 秒后尝试重新启动!' % (sec), stack=True)

    if c is not None:
        c.quit()

def app_daemon():
    """
    蚂蚁程序自动重启机制, 连接不上或遇到错误, 间隔一段时间, 重新启动蚂蚁
    """
    os.setpgrp()
    out("App Daemon: ", pidinfo())
    save_pid()
    num = 2
    while True:
        sec = num * num
        do_work(sec)
        out("Retry Work: ", pidinfo(), "num = %s, sec = %s" % (num, sec))
        sleep(sec)
        num = num + 1
        if num > 25:
            num = 3

def main(argc, argv):
    if os.fork():
        return 0

    out("Main Start: ", pidinfo())
    if argc > 1 and sys.argv[1] == 'restart':
        os.setsid()
        sys.exit(os.execlp('fw', 'fw'))
    else:
        app_daemon()


if __name__ == '__main__':
    main(len(sys.argv), sys.argv)

